// 视频监控
<template>
  <div class="video labBox">
    <laboratoryRightHeader
      :tabList="tabList"
      :commonIndex="commonIndex"
      @setTab="(event) => (commonIndex = event)"
    ></laboratoryRightHeader>
    <div class="table">
      <template v-if="commonIndex === 0">
        <div class="videList">
          <div
            class="videItem mr-30 mb-30"
            v-for="(item, index) in videList"
            :key="index"
          >
            <video
              muted
              controls="true"
              :id="`videoElement${index}`"
              height="304"
              width="542"
            ></video>
            <!-- <div class="play">
              <img
                class="pr-12"
                src="@/assets/images/laboratory/video_item2.svg"
                alt=""
                style="width: 42px; height: 50px"
              />
            </div> -->
            <!-- <div class="zhuaipai" @click="zhuapai(item)">
              <img
                class="pr-12"
                src="@/assets/images/zhuapai.svg"
                alt=""
                style="width: 20px; height: 20px"
              />
            </div> -->
          </div>
        </div>
      </template>
      <template v-if="commonIndex === 1">
        <laboratoryRightTableHeader></laboratoryRightTableHeader>
        <div class="peopleList">
          <div
            class="peopleItem fs-14 flex-common"
            v-for="(item, index) in peopleList"
            :key="index"
          >
            <img
              :src="item.image"
              alt=""
              style="width: 136px; flex-shrink: 0; height: 168px"
            />
            <div class="peopleRight ml-16">
              <div
                class="peopleLeftLabel fs-16 bold mb-20"
                style="color: #1a1e23"
              >
                {{ item.name }}
              </div>
              <div class="flex-common mb-10">
                <span class="peopleLeftLabel">学号：</span>
                <span class="cr-hui3">{{ item.studentNumber }}</span>
              </div>
              <div class="flex-common mb-10">
                <span class="peopleLeftLabel">性别：</span>
                <span class="cr-hui3">{{ item.sex === 0 ? "女" : "男" }}</span>
              </div>
              <div class="flex-common mb-10">
                <span class="peopleLeftLabel">学院：</span>
                <span class="cr-hui3">{{ item.college }}</span>
              </div>
              <div class="flex-common">
                <span class="peopleLeftLabel">进入时间：</span>
                <span class="cr-hui3">{{ item.enterTime }}</span>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import laboratoryRightTableHeader from "../laboratoryRightTableHeader.vue";
import { getliveUrl, findVideoPage, getSnapPicture } from "@/http/api";
import { mapGetters, mapActions, mapMutations, mapState } from "vuex";
import flvjs from "flv.js";
export default {
  computed: {
    ...mapState({
      floorNo: (state) => state.laboratory.floorNo,
      collegeNo: (state) => state.laboratory.collegeNo,
    }),
  },
  components: {
    laboratoryRightTableHeader,
  },
  name: "videos",
  data() {
    return {
      userInfoData: {},
      commonIndex: 0,
      tabList: [
        {
          id: 0,
          name: "实时视频",
        },
        {
          id: 1,
          name: "人脸抓拍",
        },
      ],
      peopleList: [
        {
          image:
            "https://img1.baidu.com/it/u=395380977,272417941&fm=26&fmt=auto&gp=0.jpg",
          name: "韩立",
          studentNumber: "16210810243",
          sex: 0,
          college: "环境学院环境学院",
          enterTime: "2021-09-01 12：33",
        },
        {
          image:
            "https://img1.baidu.com/it/u=395380977,272417941&fm=26&fmt=auto&gp=0.jpg",
          name: "韩立",
          studentNumber: "16210810243",
          sex: 0,
          college: "环境学院环境学院",
          enterTime: "2021-09-01 12：33",
        },
        {
          image:
            "https://img1.baidu.com/it/u=395380977,272417941&fm=26&fmt=auto&gp=0.jpg",
          name: "韩立",
          studentNumber: "16210810243",
          sex: 0,
          college: "环境学院环境学院",
          enterTime: "2021-09-01 12：33",
        },
        {
          image:
            "https://img1.baidu.com/it/u=395380977,272417941&fm=26&fmt=auto&gp=0.jpg",
          name: "韩立",
          studentNumber: "16210810243",
          sex: 0,
          college: "环境学院环境学院",
          enterTime: "2021-09-01 12：33",
        },
        {
          image:
            "https://img1.baidu.com/it/u=395380977,272417941&fm=26&fmt=auto&gp=0.jpg",
          name: "韩立",
          studentNumber: "16210810243",
          sex: 0,
          college: "环境学院环境学院",
          enterTime: "2021-09-01 12：33",
        },
      ],
      formData: {
        pageNum: 1,
        pageSize: 10,
      },
      videList: [],
    };
  },
  mounted() {
    this.userInfoData = JSON.parse(localStorage.getItem("userInfo"));
    this.initfindVideoPage();
    // this.$nextTick(() => {
    //   // this.createVideo()
    // });
  },

  methods: {
    async initfindVideoPage() {
      let params = {
        pageNum: this.formData.pageNum,
        pageSize: this.formData.pageSize,
        floorNo: this.floorNo,
        collegeNo: this.userInfoData.collegeNo,
      };
      let res = await findVideoPage(params);
      if (res.code === 20000) {
        this.videList = res.data.rows;
        res.data.rows.forEach((item, index) => {
          this.initgetliveUrl(item.deviceSerial, index);
        });
      }
    },
    createVideo(liveUrl, index) {
      if (flvjs.isSupported()) {
        var flvPlayer = flvjs.createPlayer({
          type: "flv",
          url: liveUrl, //你的url地址
        });
        let videoElement = document.getElementById("videoElement" + index);
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
        flvPlayer.play();
      }
    },
    // 获取视频流
    async initgetliveUrl(device, index) {
      let params = {
        deviceSerial: device,
        protocol: 4,
      };
      let res = await getliveUrl(params);
      if (res.code === 20000) {
        this.liveUrl = res.data;
        this.createVideo(this.liveUrl, index);
      }
    },

    /* 抓拍 */
    // async zhuapai(item) {
    //   let params = {
    //     deviceSerial: item.deviceSerial,
    //   };
    //   let res = await getSnapPicture(params);
    //   if (res.code === 20000) {
    //     this.$notify({
    //       message: '抓拍成功',
    //       duration: 1000,
    //     });
    //   }
    // },
    /* 海康视频插件部分 */
    initPlugin(codeArr) {
      // console.log("codeArr", codeArr);
      const dll = { dllPath: "./VideoPluginConnect.dll" };
      for (var i = 0; i < codeArr.length; i++) {
        let oWebControl = new WebControl({
          szPluginContainer: `playWnd${i}`, // 指定容器id
          iServicePortStart: 15900,
          iServicePortEnd: 15909,
          szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11", // 用于IE10使用ActiveX的clsid
          cbConnectSuccess: () => {
            oWebControl.JS_StartService("window", dll).then(() => {
              oWebControl.JS_SetWindowControlCallback({
                cbIntegrationCallBack: (msg) => {
                  //注：不能使用外部函数调用，无效
                  if (msg?.responseMsg?.msg?.result) {
                    const { result } = msg.responseMsg.msg;
                    if (result == 1024) {
                      oWebControl.JS_HideWnd();
                    } else if (result == 1025) {
                      oWebControl.JS_ShowWnd();
                    }
                  }
                },
              });
              //启动插件服务成功
              oWebControl.JS_CreateWnd(`playWnd${0}`, 260, 160).then(() => {
                //JS_CreateWnd创建视频播放窗口，宽高可设定
                this.initVideo(oWebControl, codeArr); // 创建播放实例成功后初始化
              });
            });
          },
          cbConnectError: () => {
            oWebControl = null;
            this.plug.example = [];
            WebControl.JS_WakeUp("VideoWebPlugin://");
            setTimeout(() => {
              this.initPlugin();
            }, 3000);
          },
        });
        this.plug.example.push(oWebControl);
      }
    },
    /* 获取公钥 */
    async initVideo(oWebControl, code) {
      const params = {
        funcName: "getRSAPubKey",
        argument: JSON.stringify({ keyLength: 1024 }),
      };
      const { responseMsg } = await oWebControl.JS_RequestInterface(params);
      if (responseMsg.data) {
        this.plug.pubKey = responseMsg.data;
        this.getVideoConfig(oWebControl);
        if (this.videoType === 0) {
          this.getClickAction(oWebControl, code);
        } else {
          this.gethistoryClickAction(oWebControl, code);
        }
      }
    },
    /* 视频插件配置项回调 */
    getVideoConfig(oWebControl) {
      const { offsetWidth, offsetHeight } = document.getElementById("playWnd0");
      // console.log("this.videoType", this.videoType);
      const configObj = {
        funcName: "init",
        argument: JSON.stringify({
          appkey: "22460346", //API网关提供的appkey
          secret: this.setEncrypt("s1IddXTZ8jSXYNUzyq8j"), //API网关提供的secret
          ip: "119.23.19.140", //API网关IP地址
          playMode: this.videoType, //播放模式（决定显示预览还是回放界面）0实时1回放
          port: 8443, //端口
          snapDir: "D:\\SnapDir", //抓图存储路径
          videoDir: "D:\\VideoDir", //紧急录像或录像剪辑存储路径
          layout: "1x1", //布局
          enableHTTPS: 1, //是否启用HTTPS协议
          encryptedFields: "secret", //加密字段
          showToolbar: 1, //是否显示工具栏
          showSmart: 1, //是否显示智能信息
          buttonIDs: "0,16,256,257,258,259,260,512,513,514,515,516,517,768,769", //自定义工具条按钮
        }),
      };
      oWebControl.JS_RequestInterface(configObj).then(() => {
        oWebControl.JS_Resize(offsetWidth, offsetHeight);
      });
    },
    /* 视频流RSA加密 */
    setEncrypt(value) {
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(this.plug.pubKey);
      return encrypt.encrypt(value);
    },
    /* 视频播放 */
    getClickAction(oWebControl, code) {
      // console.log(code, "code");
      code = code.trim();
      oWebControl.JS_RequestInterface({
        funcName: "startPreview",
        argument: JSON.stringify({
          cameraIndexCode: code, //监控点编号
          streamMode: 0, //主子码流标识：0-主码流，1-子码流
          transMode: 1, //传输协议：0-UDP，1-TCP
          gpuMode: 0, //是否启用GPU硬解，0-不启用，1-启用
          wndId: -1, //播放窗口序号（在2x2以上布局下可指定播放窗口）
        }),
      });
    },
    /* 视频回放 */
    gethistoryClickAction(oWebControl, code) {
      this.timeValue = [
        new Date(new Date(this.startValue).getTime()),
        new Date(new Date(this.endValue).getTime()),
      ];
      const startTime = Math.floor(this.timeValue[0] / 1000).toString();
      const endTime = Math.floor(this.timeValue[1] / 1000).toString();
      oWebControl
        .JS_RequestInterface({
          funcName: "startPlayback",
          argument: JSON.stringify({
            cameraIndexCode: code, //监控点编号
            startTimeStamp: startTime, //录像查询开始时间戳，单位：秒
            endTimeStamp: endTime,
            recordLocation: 1, //录像存储位置：0-中心存储，1-设备存储
            transMode: 1, //传输协议：0-UDP，1-TCP
            gpuMode: 0, //是否启用GPU硬解，0-不启用，1-启用
            wndId: -1, //播放窗口序号（在2x2以上布局下可指定播放窗口）
          }),
        })
        .then((data) => {
          // console.log("data", data);
        });
    },
    /* 销毁视频实例 */
    getDestruction() {
      this.plug.example.forEach((item) => {
        item.JS_HideWnd();
        item.JS_DestroyWnd().then((res) => {
          this.closeBtn = false;
          // console.log("close", res);
        });
        // item.JS_Disconnect().then((res) => {});
      });
    },
  },
  watch: {
    floorNo(val) {
      this.initfindVideoPage();
    },
  },
};
</script>

<style lang="scss" scoped>
.video {
  .table {
    padding: 0px 24px;
    .tableDetail {
      margin-bottom: 20px;
    }
    .videList {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      width: 100%;
      padding-top: 1%;
      .videItem {
        position: relative;
        width: 542px;
        height: 304px;
        .play {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
        .zhuaipai {
          cursor: pointer;
          position: absolute;
          // bottom: 0px;
          // right: 40%;
          bottom: 12.5%;
          right: 26%;
        }
      }
      .playWnd {
        width: 48%;
        margin: 1%;
        height: 304px;
        background: #f2f5fa;
        position: relative;
        .realtalk {
          padding: 0px 12px;
          box-sizing: border-box;
          position: absolute;
          color: #ffffff;
          right: 0px;
          top: 24px;
          display: flex;
          width: 117px;
          height: 28px;
          line-height: 30px;
          background: #00bfb1;
          opacity: 0.5;
          border-radius: 2px;
        }
        .play {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }
    .peopleList {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      width: 100%;
      margin-top: 10px;
      .peopleItem {
        width: 29.5%;
        margin-right: 24px;
        padding: 16px;
        background: #f2f5fa;
        border-radius: 4px;
        margin-bottom: 24px;
        .peopleRight {
          width: 100%;
          display: flex;
          flex-direction: column;
        }
        .peopleLeftLabel {
          text-align: left;
          width: 100px;
          flex-shrink: 0;
          color: #91a3b1;
          font-size: 14px;
          font-weight: bold;
        }
      }
      .peopleItem:nth-child(3n) {
        margin-right: 0px !important;
      }
    }
  }
}
</style>
<style lang="scss">
html:-ms-fullscreen {
  width: 100%;
}
:-webkit-full-screen {
  background: #666;
}
figure[data-fullscreen="true"] {
  max-width: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  /* hide controls on fullscreen with WebKit */
  video::-webkit-media-controls {
    display: none !important;
  }
}
</style>